# -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 10:18:46 2019

@author: leslielee
"""

import numpy as np
import matplotlib.pyplot as plt

def read_train():

    train_images_path = r"G:\Anaconda\Scripts\mnist\train-images-idx3-ubyte\train-images.idx3-ubyte"
    train_labels_path = r"G:\Anaconda\Scripts\mnist\train-labels-idx1-ubyte\train-labels.idx1-ubyte"
    train_images_bytes = open(train_images_path , 'rb').read()
    train_labels_bytes = open(train_labels_path , 'rb').read()   
    train_images = np.array([item for item in train_images_bytes[16:]])/255.0*0.99+0.01
    train_images = train_images.reshape(60000,784) #将训练图片转化为二维
    train_labels = np.array([item for item in train_labels_bytes[8:]])
    
    #重新调整标签
    targets=[]
    for train_label in train_labels:
        target = np.zeros(10) + 0.01
        target[int(train_label)] = 0.99
        targets.append(target)
    targets = np.array(targets)
        
    return train_images,targets

def read_one_train(display=True):
    train_images_path = r"G:\Anaconda\Scripts\mnist\train-images-idx3-ubyte\train-images.idx3-ubyte"
    train_images_bytes = open(train_images_path , 'rb').read() 
    train_image1 = np.array([item for item in train_images_bytes[16+784*25:784*26+16]])
    train_image2 = np.array([item for item in train_images_bytes[16+784*25:784*26+16]])/255.0*0.99+0.01
    img1 = np.reshape(train_image1,(28,28))
    img2 = np.reshape(train_image2,(28,28))
    plt.figure(1)
    plt.imshow(img1)
    plt.figure(2)    
    plt.imshow(img2)
    
    return train_image1,train_image2

def read_test():
    test_images_path = r'G:\Anaconda\Scripts\mnist\t10k-images-idx3-ubyte\t10k-images.idx3-ubyte'
    test_labels_path = r'G:\Anaconda\Scripts\mnist\t10k-labels-idx1-ubyte\t10k-labels.idx1-ubyte'
    test_images_bytes = open(test_images_path , 'rb').read()
    test_labels_bytes = open(test_labels_path , 'rb').read()   
    test_images = np.array([item for item in test_images_bytes[16:]])/255.0*0.99+0.01
    test_images = test_images.reshape(10000,784) #将训练图片转化为二维
    test_labels = np.array([item for item in test_labels_bytes[8:]])

        
    return test_images,test_labels    

if __name__ == '__main__':
    train_images_path = r"G:\Anaconda\Scripts\mnist\train-images-idx3-ubyte\train-images.idx3-ubyte"
    train_labels_path = r"G:\Anaconda\Scripts\mnist\train-labels-idx1-ubyte\train-labels.idx1-ubyte"
    
    train_images_bytes = open(train_images_path , 'rb').read()
    train_labels_bytes = open(train_labels_path , 'rb').read()
    
    #加载有效数据，并且转化为数组
    #共60000个标签，60000个图片，每个图片大小28*28=784个像素
    train_images = np.array([item for item in train_images_bytes[16:]])/255.0*0.99+0.01
    train_labels = np.array([item for item in train_labels_bytes[8:]])
    print(len(train_images))
    print(len(train_labels))
    #读取图片
    image2 = train_images[0:784].reshape(28,28)
    plt.imshow(image2)
